import sys
sys.path = ['/home/hzh/.local/lib/python3.5/site-packages/'] + sys.path
import cv2
import numpy as np
import matplotlib.pyplot as plt

from skimage.morphology import skeletonize
from skimage import data
import matplotlib.pyplot as plt
from skimage.util import invert



def skl(fp):
    img = cv2.imread(fp, 0)
    size = np.size(img)
    skel = np.zeros(img.shape, np.uint8)

    ret, img = cv2.threshold(img, 127, 255, 0)
    element = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
    done = False

    while not done:
        eroded = cv2.erode(img, element)
        temp = cv2.dilate(eroded, element)
        temp = cv2.subtract(img, temp)
        skel = cv2.bitwise_or(skel, temp)
        img = eroded.copy()

        zeros = size - cv2.countNonZero(img)
        if zeros == size:
            done = True

    plt.figure()
    plt.imshow(skel)
    plt.show()
    # cv2.imshow('skel', skel)
    # cv2.waitKey(1000)
    # cv2.destroyAllWindows()


def cv_skeletonize(img):
    """ OpenCV function to return a skeletonized version of img, a Mat object:
    ---
     hat tip to http://felix.abecassis.me/2011/09/opencv-morphological-skeleton
    """

    img = img.copy()  # don't clobber original
    skel = img.copy()

    skel[:, :] = 0
    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))

    while True:
        eroded = cv2.morphologyEx(img, cv2.MORPH_ERODE, kernel)
        temp = cv2.morphologyEx(eroded, cv2.MORPH_DILATE, kernel)
        temp  = cv2.subtract(img, temp)
        skel = cv2.bitwise_or(skel, temp)
        img[:,:] = eroded[:,:]
        if cv2.countNonZero(img) == 0:
            break

    return skel


def skl2(fp):
    img = cv2.imread(fp, 0)
    skel = cv_skeletonize(img)
    plt.figure()
    plt.imshow(skel)
    plt.show()


def skl3(fp):
    image = cv2.imread(fp, 0)
    image[image > 0] = 1
    skeleton = skeletonize(image)

    # display results
    fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(8, 4),
                             sharex=True, sharey=True)

    ax = axes.ravel()

    ax[0].imshow(image, cmap=plt.cm.gray)
    ax[0].axis('off')
    ax[0].set_title('original', fontsize=20)

    ax[1].imshow(skeleton, cmap=plt.cm.gray)
    ax[1].axis('off')
    ax[1].set_title('skeleton', fontsize=20)

    fig.tight_layout()
    plt.show()

if '__main__' == __name__:
    skl3('./data/font_tmpls/1_0.png')
